package com.itheima.Interceptor;

import com.itheima.Utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取url链接
        String url = request.getRequestURL().toString();
        //2.判断是否为登录请求
        if (url.contains("/login")) {
            log.info("登录请求,放行{}", url);
            return true;
        }
        //3.获取令牌
        String token = request.getHeader("token");
        //4.判断是否携带令牌
        if (token == null || token.equals("")) {
            //此时令牌为空或null,响应401状态码给前端
            log.info("令牌为空或null");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //5. 解析令牌  解析失败 响应401状态码
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌解析失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //6.以上情况都没出现  放行
        log.info("携带了令牌且校验通过 放行");
        return true;
    }
}
